package com.example.touchdemo.views;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.provider.MediaStore;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;


import com.example.touchdemo.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class SignatureView extends View {
    public static final String TAG = "asdf";
//    private Path mPath = new Path();
private Path mPath1 = new Path(); // 第一个手指的路径
    private Path mPath2 = new Path(); // 第二个手指的路径
    private int activePointerId1 = -1; // 当前活动手指1的ID
    private int activePointerId2 = -1; // 当前活动手指2的ID
    private float[] mLastTouchPos = new float[2]; // 上一次触摸位置缓存
    private Paint mPaint = new Paint();
    //位图的绘制内容输出者：画布
    private Canvas mCanvas;
    //用来存放绘制内容的位图
    private Bitmap mCacheBitmap;
    //上下文
    private Context mContext;

    public SignatureView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(10);
        mPaint.setColor(getResources().getColor(R.color.red, null));
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mCacheBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mCacheBitmap);
        mCanvas.drawColor(Color.WHITE);
    }

//    @Override
//    public boolean onTouchEvent(MotionEvent event) {
////        switch (event.getAction()) {
//            int index=event.getActionIndex();
//            switch (event.getActionMasked()){
//            case MotionEvent.ACTION_DOWN:
//                mPath.moveTo(event.getX(), event.getY());
//                Log.e(TAG, "ACTION_DOWN getX = " + event.getX() + " getY = " + event.getY());
//                break;
//            case MotionEvent.ACTION_MOVE:
//                mPath.lineTo(event.getX(), event.getY());
//                if (event.getPointerCount()==2) {
//                    x2 = event.getX(1);
//                    y2 = event.getY(1);
//
//                    x1 = event.getX(0);
//                    y1 = event.getY(0);
//                    Log.d(TAG, "=======pointer======move" + "(" + x1 + "," + y1 + "),(" + x2 + "," + y2 + ")");
//                    Log.e(TAG, "ACTION_MOVE getX = " + event.getX() + " getY = " + event.getY());
//                }
//                break;
//            case MotionEvent.ACTION_UP:
//                Log.e(TAG, "ACTION_UP getX = " + event.getX() + " getY = " + event.getY());
//                break;
//        }
//        //真正负责绘制签名笔迹的画布，在这里接收路径mPath，以及事先定义好的颜料
//        mCanvas.drawPath(mPath, mPaint);
//        invalidate();
//        return true;
//    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getActionMasked();
        int pointerIndex = event.getActionIndex();

        switch (action) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_POINTER_DOWN:
                int pointerId = event.getPointerId(pointerIndex);
                if (activePointerId1 == -1) { // 如果还没有手指在屏幕上
                    activePointerId1 = pointerId;
                    mPath1.moveTo(event.getX(pointerIndex), event.getY(pointerIndex));
                    mLastTouchPos[0] = event.getX(pointerIndex);
                    mLastTouchPos[1] = event.getY(pointerIndex);
                } else if (activePointerId2 == -1 && event.getPointerCount() > 1) { // 如果只有一个手指在屏幕上，且现在有第二个手指触屏
                    activePointerId2 = pointerId;
                    mPath2.moveTo(event.getX(pointerIndex), event.getY(pointerIndex));
                }
                break;

            case MotionEvent.ACTION_MOVE:
                if (activePointerId1 != -1) {
                    int index1 = event.findPointerIndex(activePointerId1);
                    if (index1 >= 0) {
                        mPath1.lineTo(event.getX(index1), event.getY(index1));
                        mLastTouchPos[0] = event.getX(index1);
                        mLastTouchPos[1] = event.getY(index1);
                    }
                }

                if (activePointerId2 != -1) {
                    int index2 = event.findPointerIndex(activePointerId2);
                    if (index2 >= 0) {
                        mPath2.lineTo(event.getX(index2), event.getY(index2));
                    }
                }
                break;

            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
                int pointerIdUp = event.getPointerId(pointerIndex);
                if (pointerIdUp == activePointerId1) {
                    activePointerId1 = -1;
                } else if (pointerIdUp == activePointerId2) {
                    activePointerId2 = -1;
                }
                break;

            case MotionEvent.ACTION_CANCEL:
                activePointerId1 = -1;
                activePointerId2 = -1;
                break;
        }

        // 绘制路径
        mCanvas.drawPath(mPath1, mPaint); // 绘制第一个手指的路径
        mCanvas.drawPath(mPath2, mPaint); // 绘制第二个手指的路径

        invalidate();
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Log.e(TAG, "onDraw canvas = " + canvas);
        canvas.drawPath(mPath1, mPaint);
        canvas.drawPath(mPath2, mPaint);
    }

    /**
     * 清空
     */
    public void clear() {
        Log.e(TAG, "clear()");
        if (mPath1 != null&&mPath2!=null) {
            Log.e(TAG, "before clear mPath isEmpty => " + mPath1.isEmpty());
            mPath1.reset();
            mPath2.reset();
            mCanvas.drawColor(Color.WHITE);
            Log.e(TAG, "after clear mPath isEmpty => " + mPath1.isEmpty());
            invalidate();
        }
    }

    public void save() {
        //创建一个文件用于存放图片
        File file = new File(mContext.getExternalFilesDir(null) + "testSign.png");
        if (file.exists()) {
            file.delete();
        }
        OutputStream outputStream = null;
        try {
            //输出到这个文件
            outputStream = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(mContext, "保存异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        //压缩形成输出流
        mCacheBitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
        Toast.makeText(mContext, "保存成功!path:" + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
    }

    public void saveImageToGallery() {
        String savedImageURL = MediaStore.Images.Media.insertImage(
                mContext.getContentResolver(),
                mCacheBitmap,
                "testSign",
                "testSign save"
        );
        Toast.makeText(mContext, "保存成功! URL:" + savedImageURL, Toast.LENGTH_SHORT).show();
    }
}
